#include "Database.h"

// Singleton database -----------------------------------------------------
Database* Database::pInstance = NULL;

int cb_query(void* value, int argc, char** argv, char** colName)
{
	value = *argv;
	return 0;
}

void Database::initialize(std::string filename)
{

}
Database::Database()
{
}
Database::~Database()
{
	db_close();
}

Database* Database::getSinglePtr()
{
	return pInstance;
}
// end Singleton database -------------------------------------------------

// Database access
bool Database::db_init(std::string name)
{
	int result = sqlite3_open(name.c_str(),&db);
	if(result)
	{
		std::cout << "Cannot open database: " << sqlite3_errmsg(db) << std::endl;
		db_close();
		ArmyEngine::getSingletonPtr()->exit();
	}
	db_exec("CREATE TABLE soldiers(id INTEGER PRIMARY KEY ASC, health INTEGER, maxhealth INTEGER);");
	db_exec("CREATE TABLE armies(id INTEGER PRIMARY KEY ASC)"); // @TODO - implement multiple association and enemy
}
bool Database::db_exec(std::string command, int (*cb)(void*,int, char**, char**))
{
	char* err;
	int result = sqlite3_exec(db, command.c_str(), cb, 0, &err);
	if(result != SQLITE_OK)
	{
		std::cout << "SQL error: " << err << std::endl;
		sqlite3_free(err);
	}
}
bool Database::db_close()
{
	sqlite3_close(db);
}
// end Database access ----------------------------------------------------

// Database functions
void Database::addArmy(std::string name)
{
	std::stringstream ss;
	ss << "INSERT INTO armies VALUES(NULL);";
	db_exec(ss.str());
}
int Database::addSoldier(std::string army, int health)
{
	std::stringstream ss;
	ss << "INSERT INTO soldiers VALUES(NULL," << health << "," << health << ");";
	db_exec(ss.str());
	return 0;
}

char** Database::s_getAttributes(int soldier, std::string attrs)
{
	char** result;
	std::stringstream ss;
	ss << "SELECT " << attrs << " FROM soldiers WHERE key=" << soldier << ";";
	db_exec(ss.str());
	return result;
}

int Database::s_getTarget(int soldier);
// end Database functions